<template>
  <div class="home-page-container">
    <div class="top">
      <div class="left">
        <el-form ref="oilStationDetail" :model="oilStationDetail" label-width="120px">
          <!-- 登录用户是油站或者修改的情况-->
          <el-form-item label="油站名称：" v-if="!loginInfo.company || configId">
            <span class="value">{{oilStationDetail.gasName || ''}}</span>
          </el-form-item>
          <!--商户新增位置排序的情况-->
          <el-form-item label="油站名称：" v-if="loginInfo.company && !configId">
            <el-select filterable placeholder="请选择" v-model="oilStationDetail.gasId" @change="gasChange">
              <el-option
                  v-for="item in oilStations"
                  :key="item.gasId"
                  :label="item.gasName"
                  :value="item.gasId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="剩余可用天数：">
            <span class="value">{{nowSurplusDays || 0}}天</span>
          </el-form-item>
          <el-form-item label="置顶位置：">
            <el-select filterable placeholder="请选择" v-model="oilStationDetail.customLocation">
              <el-option
                  v-for="item in customLocations"
                  :key="item"
                  :label="`置顶位置${item}`"
                  :value="Number(item)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生效时间：">
            <el-date-picker
                type="dates"
                v-model="oilStationDetail.dates"
                placeholder="选择一个或多个日期"
                :picker-options="timePickerOptions"
                @change="timeChange"
                value-format="timestamp"
                :disabled="!oilStationDetail.customLocation"
                >
            </el-date-picker>
            <div class="tip">生效时间将于凌晨00点生效</div>
          </el-form-item>
        </el-form>
        <!--根据生效时间展示对应的最大辐射半径-->
        <div class="list-box" v-if="oilStationDetail.vos.length > 0">
          <el-table stripe size="small" :data="oilStationDetail.vos" style="width: 100%;margin-bottom:20px;" border className="table-header">
            <el-table-column label="生效时间" align="center">
              <template slot-scope="scope">
                {{scope.row.startTime | formatTime('YYYY-MM-DD HH:mm:ss')}}
                {{scope.row.endTime ? `至` : ''}}
                {{scope.row.endTime | formatTime('YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column prop="radiusDistance" label="最大辐射半径" align="center">
              <template slot-scope="scope">
                {{scope.row.radiusDistance ? `${scope.row.radiusDistance}公里` : '不可用'}}
                <el-tooltip class="item" effect="dark" v-if="scope.row.radiusDistance === 0" content="当前日期最大辐射半径为0，不扣除权益天数" placement="top-start">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                <!-- 变动内容-->
                {{scope.row.changeContent ? '(' + scope.row.changeContent + ')' : ''}}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="footer">
          <el-button @click="back" >返回</el-button>
          <el-button type="primary" @click="submitOperation" :loading="submitLoading">提交</el-button>
        </div>
      </div>
      <div class="right">
        <img src="https://web.czb365.com/ty/merchant/sample_graph.png" class="sample-graph" alt="">
      </div>
    </div>
  </div>
</template>

<script>
import { gasRankConfigAdd, gasRankConfigQuery, getSurplusDays, gasRankConfigDistance, gasRankConfigUpdate, getCustomLocationsList, getAllGasInfoList } from '@/api/market'
export default {
  name: "locationSortAdd",
  data () {
    return {
      configId: '', // 当前排序ID 修改时用
      loginInfo: {}, // 登录油站信息
      nowSurplusDays: '',// 剩余天数
      oilStationDetail: {
        gasId: '',
        gasName: '',
        surplusDays: '', // 剩余实际天数（修改时包含修改的天数）
        customLocation: 1, // 选中的位置
        dates: [] , // 选中的时间点
        vos: [ // 选中的时间范围以及辐射半径
          // {
          //   startTime: '2020-9-12',
          //   endTime: '2020-9-20',
          //   radiusDistance: 0,
          //   changeContent: 'radiusDistance'
          // }
        ]
      }, // 当前登录油站信息
      submitLoading: false,
      customLocations: [],
      oilStations: [], // 油站列表
      timePickerOptions: { // 时间选择处理
        disabledDate: (time) => {
          // 当前时间之前不可选择
          return time.getTime() < Date.now()
        }
      }
    }
  },
  created () {
    this.configId = this.$route.query.configId || null // 获取当前排序ID 修改时
    // 获取登录用户信息
    this.loginInfo = JSON.parse(sessionStorage.getItem('loginInfo') || '{}')
  },
  mounted () {
    if (this.configId) {
      // 修改的情况
      //获取登录油站信息
      this.gasRankConfigGet()
      this.$route.meta.title = '修改排序'
    } else {
      this.$route.meta.title = '新增排序'
      // 新增的情况
      if (this.loginInfo.company) {
        // 商户的情况
        // 如果为页面跳转过来，需获取油站ID
        this.oilStationDetail.gasId = this.$route.query.gasId || ''
        // 获取油站列表
        this.getAllGasInfoListAjax()
      } else {
        // 油站的情况
        // 油站直接获取当前登录油站信息
        this.oilStationDetail.gasName = this.loginInfo.gasName || ''
        this.oilStationDetail.gasId = this.loginInfo.gasId || ''
        // 查询剩余天数
        this.getSurplusDaysAjax()
      }
    }
    // 获取排序位置列表项
    this.getCustomLocationsListAjax()
    // // 登录的若是商户新增需要查询油站列表
    // if(this.loginInfo.company && !this.configId) {
    //   // 如果为页面跳转过来，需获取油站ID
    //   this.oilStationDetail.gasId = this.$route.query.gasId || ''
    //   // 获取油站列表
    //   this.getAllGasInfoListAjax()
    // } else {
    //   // 油站直接获取当前登录油站信息
    //   this.oilStationDetail.gasName = this.loginInfo.gasName || ''
    //   this.oilStationDetail.gasId = this.loginInfo.gasId || ''
    //   if (!this.configId) {
    //     // 查询剩余天数
    //     this.getSurplusDaysAjax()
    //   } else {
    //     // 获取登录油站信息
    //     this.gasRankConfigGet()
    //   }
    // }
    // if (this.configId) {
    //   // 获取登录油站信息
    //   this.gasRankConfigGet()
    // }
  },
  watch: {
    'oilStationDetail.dates': {
      handler (val) {
        let allCountDays = this.oilStationDetail.surplusDays
        // 修改的情况，需要加上当前修改的天数
        if (this.oilStationDetail.currentDays) {
           allCountDays += this.oilStationDetail.currentDays
        }
        if (val && val.length > allCountDays) {
          this.$message.warning('选择的日期超过当前剩余天数')
          this.oilStationDetail.dates.pop()
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取剩余天数
    async getSurplusDaysAjax () {
      try {
        let params = {
          gasId: this.oilStationDetail.gasId
        }
        const { code, result }  = await getSurplusDays(params)
        if (code !== 200) return
        this.oilStationDetail.surplusDays = result || ''
        this.nowSurplusDays = result || ''
      } catch (err) {
        console.log(err)
      }
    },
    // 获取油站列表
    async  getAllGasInfoListAjax () {
      try{
          const {code, result} = await getAllGasInfoList ()
        if (code !== 200) return
        this.oilStations = result || []
        // 如果油站ID为空，默认选择第一个油站
        if (!this.oilStationDetail.gasId) {
          this.oilStationDetail.gasId= this.oilStations[0].gasId
        }
        // 查询剩余天数
        this.getSurplusDaysAjax()
      } catch (err) {
        console.log(err)
      }
    },
    // 获取排序位置列表项
    async getCustomLocationsListAjax () {
      try {
        const { code, result } = await getCustomLocationsList()
        if (code !== 200) return
        this.customLocations = result || {}
      } catch (err) {
        console.log(err)
      }
    },
    // 获取登录油站信息 (修改的情况)
    async gasRankConfigGet () {
      try {
        let param = {
          configId: this.configId // 修改的情况
        }
        const {code, result } = await gasRankConfigQuery (param)
        if (code !== 200) return
        this.oilStationDetail = result || {}
        // 查询剩余天数
        this.getSurplusDaysAjax()
      }catch(err) {
        console.log(err)
      }
    },
      // 点击提交
    submitOperation () {
      if (!this.oilStationDetail.gasId) {
        this.$message.warning('请选择油站～');
        return false
      }
      if (!this.oilStationDetail.customLocation) {
        this.$message.warning('请选择置顶位置～');
        return false
      }
      if (this.oilStationDetail.dates.length === 0) {
        this.$message.warning('请选择生效时间～');
        return false
      }
      // 修改的情况
      if (this.configId) {
        this.update()
      } else {
        // 添加
        this.add()
      }
    },
    // 修改提交
    async update () {
      try{
        this.submitLoading = true
        let params = {
          configId: this.configId,
          customLocation: this.oilStationDetail.customLocation,  // 选中的排序位置
          gasId: this.oilStationDetail.gasId, // 油站ID
          radiusDistanceVos: this.oilStationDetail.vos, // 日期和辐射半径
          sysSource: 2, // 系统来源，1赫拉2商户中心
        }
        const { code, result } = await gasRankConfigUpdate(params)
        if(code !== 200) return
        if (result.vos.length === 0) {
          this.$message.success('修改成功')
          this.$router.replace('/marketCenter/locationSort')
        } else {
          this.$alert('当前时间段油站半径发生改变，请重新查看', '半径改变', {
            confirmButtonText: '知道了',
            callback: () => {
              this.oilStationDetail.vos = result.vos
            }
          })
        }

      }catch(err){
        console.log(err)
      }finally{
        this.submitLoading = false
      }
    },
    // 添加提交
    async add () {
      this.submitLoading = true
      try{
        let params = {
          customLocation: this.oilStationDetail.customLocation, // 选中的排序位置
          gasId: this.oilStationDetail.gasId, // 油站ID
          radiusDistanceVos: this.oilStationDetail.vos, // 日期和辐射半径
          sysSource: 2, // 系统来源，1赫拉2商户中心
        }
        const { code, result } = await gasRankConfigAdd(params)
          if(code !== 200) return
          if (result.vos.length === 0) {
            this.$message.success('添加成功');
            this.$router.replace('/marketCenter/locationSort')
          } else {
            this.$alert('当前时间段油站半径发生改变，请重新查看', '半径改变', {
              confirmButtonText: '知道了',
              callback: () => {
                this.oilStationDetail.vos = result.vos
              }
            })
          }
      }catch(err){
        console.log(err)
      }finally{
        this.submitLoading = false
      }
    },
    // 根据选择时间进行可配置半径查询
    async getgasRankConfigDistance () {
      let data ={
        params: this.oilStationDetail.dates.join(','), // 选择的时间点
        gasId: this.oilStationDetail.gasId || '', // 油站id
        configId: this.configId || ''
      }
      try {
        const { code, result } = await gasRankConfigDistance(data)
        if (code !== 200) return
          // 更新列表显示最新辐射半径信息
        this.oilStationDetail.vos = result.vos || []
      } catch(err) {
        console.log(err)
      }
    },
    // 时间改变时触发
    timeChange () {
      if (!this.oilStationDetail.dates || this.oilStationDetail.dates.length === 0) {
        this.$message.warning('请选择生效时间～')
        this.oilStationDetail.vos = []
        return false
      }
      // 选择了时间点后进行位置半径查询
      this.getgasRankConfigDistance()
    },
    // 查询剩余天数
    gasChange () {
      this.oilStationDetail.dates = []
      this.oilStationDetail.vos = []
      // 查询剩余天数
      this.getSurplusDaysAjax()
    },
    // 返回
    back () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.home-page-container {
  min-width: 1066px;
  background: #ffffff;
  padding: 32px 38px;
  .top {
    display: flex;
    /*justify-content: space-between;*/
  }
  /deep/ .el-table thead tr th{
    background: #F8F9FD;
  }
}
.left {
  min-width: 615px;
  .item {
    font-size: 14px;
    .text {
      color: #222222;
      width: 120px;
    }
  }
  .value {
    color: #606266;
  }
  /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  /deep/ .el-select {
    width: 100%;
  }
  .tip {
    color: #E31937;
    font-size: 14px;
  }
  .list-box {
    padding-left: 36px;
  }
}
.right {
  padding-left: 100px;
  .sample-graph {
    width: 251px;
    height: 488px;
  }
}
.table-header {
  background: #F5F7FA;
}
.footer {
  width: 100%;
  padding-top: 50px;
  display: flex;
  justify-content: center;
  /deep/ .el-button {
    padding: 10px 49px;
  }
  /deep/ .el-button+.el-button {
    margin-left: 40px;
  }
}
.el-icon-question {
  color:#A6A6A6;
}
</style>
